package com.heima.media.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.*;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.media.service.IWmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.*;
import java.util.List;


/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-06-28
 */
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Autowired
    private IWmUserService userService;


    @Override
    public ResponseResult listByCondition(WmNewsPageDto dto) {
        //判断是否有登录人
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //条件查询
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();

        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //
        if (dto.getChannelId() != null) {
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //日期起始
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            queryWrapper.ge(WmNews::getPublishTime, dto.getBeginPubDate());
            queryWrapper.le(WmNews::getPublishTime, dto.getEndPubDate());
        }
        //模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            queryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        //自媒体发布时间排序   倒序
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        Page<WmNews> page1 = this.page(page, queryWrapper);

        return new PageResponseResult(dto.getPage(), dto.getSize(), page1.getTotal(), page1.getRecords());
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //判断是否有登录人
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //保存自媒体文章
        //判断是否有id  有修改  无新增
        if (dto.getId() != null) {
            //有修改
            //删除以关联素材的关系
            deleteRelation(dto.getId());
        }

        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);

        wmNews.setUserId(user.getUserId());
        wmNews.setType(dto.getType());//文章封面类型  0 无图 1 单图 3 多图 -1 自动
        wmNews.setCreatedTime(new Date());//创建时间
        wmNews.setSubmitedTime(new Date());//提交时间
        wmNews.setStatus(dto.getStatus());//状态 提交为1  草稿为0
//        wmNews.setReason();//先不处理
//        wmNews.setArticleId();
        List<ImageDto> caverImageList = dto.getImages();
        wmNews.setImages(JSON.toJSONString(caverImageList));
        wmNews.setEnable(true);


        //文章内容获取所有图片  放入List集合
        List<ImageDto> contentImagesList = getImageListFromContent(dto.getContent());


        //封面图片自动从文章获取
        if (dto.getType() == -1) {
            int size = contentImagesList.size();
            if (size == 0) {
                //文章没图片
                wmNews.setType(0);
                caverImageList = contentImagesList;
            } else if (size > 0 && size < 3) {
                //0张<图片<3张
                wmNews.setType(1);
                caverImageList = contentImagesList.subList(0, 1);
            } else if (size >= 3) {
                //图片>=3张
                wmNews.setType(3);
                caverImageList = contentImagesList.subList(0, 3);
            }
            wmNews.setImages(JSON.toJSONString(caverImageList));
        }


        this.saveOrUpdate(wmNews);//有id update

        //是否为草稿
        if (dto.getStatus() == 1) {
            //关联内容图片与素材关系  contentImagesList
            saveRelation(contentImagesList, wmNews.getId(), 0);

            //关联封面图片与素材关系  caverImageList
            saveRelation(caverImageList, wmNews.getId(), 1);

        }

        //调用自媒体的审核方法
        auditService.audit(wmNews);

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findPageByName(NewsAuthDto dto) {

        // 构建查询条件
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        // 根据标题模糊查询
        if (!StringUtils.isEmpty(dto.getTitle())) {
            query.like(WmNews::getTitle, dto.getTitle());
        }
        // 根据状态查询
        if (dto.getStatus() != null) {
            query.eq(WmNews::getStatus, dto.getStatus());
        }
        // 根据发布时间倒序排列
        query.orderByDesc(WmNews::getPublishTime);

        // 构建分页条件
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        // 分页查询
        Page<WmNews> iPage = this.page(page, query);
        List<WmNews> newsList = iPage.getRecords();
        // 返回通用的分页响应
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                iPage.getTotal(), newsList);
        return result;
    }

    @Override
    public ResponseResult<WmNewsVo> findNewsVoById(Integer id) {
        // 根据id查询文章
        WmNews wmNews = this.getById(id);
        // 查询作者名称
        WmUser wmUser = userService.getById(wmNews.getUserId());
        // 构建vo对象
        WmNewsVo vo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews, vo);
        vo.setAuthorName(wmUser.getName());
        // 通用响应
        return ResponseResult.okResult(vo);
    }


    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.upDownTopic}")
    public String upDownTopic;


    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {

        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //判断是否有文章id
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //根据id持否能查询出对象
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //判断自媒体体文章是否是当前登录人登录
        if (user.getUserId().intValue() != wmNews.getUserId().intValue()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        //判断是否发布
        if (wmNews.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.No_UP_DOWN);
        }

        //1上架   0下架
        wmNews.setEnable(dto.getEnable() == 1 ? true : false);
        this.updateById(wmNews);


        //kafka发送消息
        Long articleId = wmNews.getArticleId();

        Map map = new HashMap();
        map.put("articleId", articleId);
        map.put("enable", dto.getEnable() == 1 ? true : false);

        kafkaTemplate.send(upDownTopic, JSON.toJSONString(map));
        log.info("上下架后想kafka中方入数据");
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult auth(NewsAuthDto dto, int type) {
        // 根据文章id查询
        WmNews wmNews = this.getById(dto.getId());
        // 如果是审核通过,修改状态为4
        if (type == 1) {
            // 发布文章
            Long articleId = auditService.saveApArticle(wmNews);
            wmNews.setArticleId(articleId);
            wmNews.setStatus(4);
            this.updateById(wmNews);

        } else {
            // 审核不通过,记录拒绝原因
            wmNews.setStatus(2);
            wmNews.setReason(dto.getMsg());
            this.updateById(wmNews);
        }
        return ResponseResult.okResult();
    }


    @Autowired
    private IAuditService auditService;

    private void saveRelation(List<ImageDto> caverImageList, Integer newsId, int type) {

        int ord = 0;

        for (ImageDto imageDto : caverImageList) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(imageDto.getId());
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterial.setOrd(ord);
            ord++;
            wmNewsMaterialService.save(wmNewsMaterial);
        }
    }


    private List<ImageDto> getImageListFromContent(String content) {
        List<ContentDto> contentDtoList = JSON.parseArray(content, ContentDto.class);

        List<ImageDto> imageDtoList = new ArrayList<>();

        for (ContentDto contentDto : contentDtoList) {
            if (contentDto.getType().equals("image")) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                imageDtoList.add(imageDto);
            }
        }
        return imageDtoList;
    }


    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;


    //根据自媒体文章id删除文章和素材关系
    private void deleteRelation(Integer newsId) {
        //条件查询
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getNewsId, newsId);

        wmNewsMaterialService.remove(queryWrapper);
    }
}
